<template>
  <div class="partnerMain">
    <div class="partnerLoginedMain">
      <!-- Table搜索 -->
      <el-form :inline="true" :model="formSerach"
      class="formSerach-inline right">
        <!-- 日期 -->
        <el-form-item :label="$t('order.date')">
          <date-vue :dateDefault="formSerach.dateArr"
          @ListenTimeArr="listenTimeArr" style="width: 250px" />
        </el-form-item>
        <el-form-item class="form-item-min">
            <span class="label">{{$t('quotation.symbol')}} </span>
            <el-popover
              placement="bottom"
              width="150"
              trigger="focus"
              class="historyData"
              v-model="historyVisible">
              <ul class="historyList codeList" v-if="formSerach.coinCode">
                <li
                  v-for="(item, index) in codeList"
                  :key="index"
                  @click="handleSelectCodeList(item, index)"
                  style="font-size: 12px;">
                  {{ item.symbolFormat }}
                  <!-- <img
                    v-if="item.crossChain"
                    src="../../../../../../static/img/chain/celian.png"
                    class="iconfont celianImg"/> -->
                </li>
              </ul>
              <ul class="historyList" v-else>
                <li
                  v-for="(item, index) in historyList"
                  :key="index"
                  @click="handleSelectHistory(item, index)"
                  style="font-size: 12px;">
                  {{ item }}
                </li>
                <li v-if="historyList && historyList.length === 0" style="cursor: default;">
                  <span style="opacity: 0.5; font-size: 12px;">{{ $t('public.noHistory') }}</span>
                </li>
              </ul>
              <!-- 交易对 -->
              <el-input
                :placeholder="$t('order.coinInput')"
                v-model="formSerach.coinCode"
                clearable
                style="width: 150px;"
                ref="historyInput"
                slot="reference"
                class="coinInput"
                @input="inputchange($event)"
                @clear="handleInitSearch"
                @keyup.native="handleShowCodeList"
              >
              </el-input>
            </el-popover>
          </el-form-item>
        <!-- 方向 -->
        <el-form-item :label="$t('order.tradeDirection')" class="form-item-min">
          <el-select v-model="formSerach.direction" style="width: 80px">
            <el-option v-for="item in directionList"
            :key="item.value"
            :label="$t(`order.${item.language}`)"
            :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 用户账户 -->
        <el-form-item :label="$t('order.account')" class="form-item-min">
          <el-input v-model="formSerach.accountNo" style="width: 120px"
          clearable
          :placeholder="$t('order.accountName')"></el-input>
        </el-form-item>
        <!-- 清除条件 -->
        <el-form-item style="margin-right: 0">
          <el-button type="info"
          plain @click="handleClearSubmit">{{ $t('order.clearCondition') }}</el-button>
        </el-form-item>
        <!-- 搜索 -->
        <el-form-item style="margin-right: 0">
          <el-button
          type="primary" @click="handleSerachSubmit(1)">{{$t('order.search')}}</el-button>
        </el-form-item>
        <!-- 导出 -->
        <el-form-item style="margin-right: 0">
          <span
            class="item export fr"
            @click="handleExportOrder">
            <span>
              {{ $t('order.export') }}
              <i class="iconfont icon-daochu"></i>
            </span>
          </span>
        </el-form-item>
      </el-form>
      <!-- table 数据 -->
      <div class="tablebox mt">
        <el-table
          :data="tableData"
          v-loading="loading"
          :empty-text="$t('myWallet.noData')"
          border
          row-key="id"
          :default-sort = "{prop: 'orderTime', order: 'descending'}"
          style="width: 100%">
          <!-- 交易对 -->
          <el-table-column
            min-width="170px"
            fixed="left"
            :label="$t('order.symbol')">
            <template slot-scope="props">
              <span>
                {{props.row.symbol}}
              </span>
            </template>
          </el-table-column>
          <!-- 成交价 -->
          <el-table-column
          :label="$t('order.subAvgPrice')">
            <template slot-scope="props">
              <span>
                {{props.row.dealPrice}}
              </span>
            </template>
          </el-table-column>
          <!-- 成交数量 -->
          <el-table-column
            width="70px"
            :label="$t('order.subAvgCount')">
            <template slot-scope="props">
              <span>
                {{props.row.dealCount}}
              </span>
            </template>
          </el-table-column>
          <!-- 成交金额 -->
          <el-table-column :label="$t('order.subAvgMoney')">
            <template slot-scope="props">
              <span>{{props.row.dealAmount}}</span>
            </template>
          </el-table-column>
          <!-- 成交时间 -->
          <el-table-column
            width='160px'
            :label="$t('order.subAvgTime')">
            <template slot-scope="props">
              {{props.row.dealTime | dateFormatBIH}}
            </template>
          </el-table-column>
          <!-- 买方账号 -->
          <el-table-column
            width='110px'
            :label="$t('order.bidAccountNo')">
            <template slot-scope="props">
              <span>
                {{props.row.bidAccountNo}}
              </span>
            </template>
          </el-table-column>
          <!-- 买方收款账号 -->
          <el-table-column
            width='110px'
            :label="$t('order.bidReceiver ')">
            <template slot-scope="props">
              <span>
                {{props.row.bidReceiver}}
              </span>
            </template>
          </el-table-column>
          <!-- 买方手续费 -->
          <el-table-column
            width='100px'
            :label="$t('order.bidCharge ')">
            <template slot-scope="props">
              <span>
                {{props.row.bidCharge}}
              </span>
            </template>
          </el-table-column>
          <!-- 买方渠道 -->
          <el-table-column :label="$t('order.bidRef ')">
            <template slot-scope="props">
              <span>
                {{props.row.bidRef}}
              </span>
            </template>
          </el-table-column>
          <!-- 买方订单Id -->
          <el-table-column
            width='110px'
            :label="$t('order.bidOrderId ')">
            <template slot-scope="props">
              <span>
                {{props.row.bidOrderId}}
              </span>
            </template>
          </el-table-column>
          <!-- 买方订单txId -->
          <el-table-column
            fixed="right"
            min-width="105px"
            :label="$t('order.bidOrderTrxId ')">
            <template slot-scope="props">
              <div class="tridbox">
                <span class="fn-text1" style="width: 56%; display: inline-block">
                  {{props.row.bidOrderTrxId}}
                </span>
                <span
                  v-clipboard:copy="props.row.bidOrderTrxId"
                  v-clipboard:success="onCopy"
                  v-clipboard:error="onError"
                  >{{ $t('activityChristmas2018.copy') }}</span>
              </div>
            </template>
          </el-table-column>
          <!-- 买方结算txId -->
          <el-table-column
            fixed="right"
            min-width="105px"
            :label="$t('order.bidTrxId ')">
            <template slot-scope="props">
              <div class="tridbox">
                <span class="fn-text1" style="width: 56%; display: inline-block">
                  {{props.row.bidTrxId}}
                </span>
                <span
                  v-clipboard:copy="props.row.bidTrxId"
                  v-clipboard:success="onCopy"
                  v-clipboard:error="onError"
                  >{{ $t('activityChristmas2018.copy') }}</span>
              </div>
            </template>
          </el-table-column>
          <!-- 卖方账号 -->
          <el-table-column
            width='110px'
            :label="$t('order.askAccountNo ')">
            <template slot-scope="props">
              <span>
                {{props.row.askAccountNo}}
              </span>
            </template>
          </el-table-column>
          <!-- 卖方收款账号 -->
          <el-table-column
            width='120px'
            :label="$t('order.askReceiver ')">
            <template slot-scope="props">
              <span>
                {{props.row.askReceiver}}
              </span>
            </template>
          </el-table-column>
          <!-- 卖方手续费 -->
          <el-table-column
            width='100px'
            :label="$t('order.askCharge ')">
            <template slot-scope="props">
              <span>
                {{props.row.askCharge}}
              </span>
            </template>
          </el-table-column>
          <!-- 卖方渠道 -->
          <el-table-column :label="$t('order.askRef ')">
            <template slot-scope="props">
              <span>
                {{props.row.askRef}}
              </span>
            </template>
          </el-table-column>
          <!-- 卖方订单Id -->
          <el-table-column
            width='110px'
            :label="$t('order.askOrderId ')">
            <template slot-scope="props">
              <span>
                {{props.row.askOrderId}}
              </span>
            </template>
          </el-table-column>
          <!-- 卖方订单txId -->
          <el-table-column
            fixed="right"
            min-width="105px;"
            :label="$t('order.askOrderTrxId ')">
            <template slot-scope="props">
              <div class="tridbox">
                <span class="fn-text1" style="width: 56%; display: inline-block">
                  {{props.row.askOrderTrxId}}
                </span>
                <span
                  v-clipboard:copy="props.row.askOrderTrxId"
                  v-clipboard:success="onCopy"
                  v-clipboard:error="onError"
                  >{{ $t('activityChristmas2018.copy') }}</span>
              </div>
            </template>
          </el-table-column>
          <!-- 卖方结算txId -->
          <el-table-column
            width='105px'
            fixed='right'
            :label="$t('order.askTrxId ')">
            <template slot-scope="props">
              <div class="tridbox">
                <span class="fn-text1" style="width: 56%; display: inline-block">
                  {{props.row.askTrxId}}
                </span>
                <span
                  v-clipboard:copy="props.row.askTrxId"
                  v-clipboard:success="onCopy"
                  v-clipboard:error="onError"
                  >{{ $t('activityChristmas2018.copy') }}</span>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagebox center ptb">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="formSerach.currPage"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="formSerach.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="formSerach.totalCount">
          </el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import moment from 'moment';
// 公用JS
import { chainLogo } from '@/utils/wallet';
// 模版
import dateVue from './time';


export default {
  name: 'dataTableModule',
  data() {
    return {
      loading: false,
      tableData: [], // 列表数据
      historyVisible: false,
      historyList: [], // 历史数据
      isClick: true, // 避免重复点击
      formSerach: { // 查询数据
        dateArr: [],
        direction: '', // 方向
        coinType: '', // 主链
        account: '', // 用户账户
        currPage: 1, // 当前页码
        pageSize: 10, // 每页条数
        totalCount: 0, // 总条数-用于显示页数
        channel: '', // 渠道方
        role: '', // 交易角色
        symbolId: 230
      },
      // 方向
      directionList: [],
      // 币种
      coinTypeList: [],
      channelList: [],
      roleList: [],

      codeList: [], // 查询列表
      codeListData: [], // 币种列表
    };
  },
  props: {
  },
  watch: {
    '$store.state.app.language': function change() {
      this.dataReset();
    },
  },
  components: {
    dateVue, // 日期控件
  },
  computed: {
  },
  created() {
    const yesdate = moment(new Date()).add(-1, 'd').format('Y-MM-DD');
    this.formSerach.dateArr = [yesdate, moment(new Date()).format('Y-MM-DD')]; // 日期范围
    this.formSerach.coinCode = '';
    this.dataReset();
  },
  mounted() {
    // 获取搜索历史记录
    const historyData = localStorage.getItem('historyDatas');
    this.historyList = historyData ? JSON.parse(historyData) : [];
    this.codeListData = this.$store.state.app.codeList.list;
    this.$nextTick(() => {
      this.formSerach.currPage = 1;
      this.setDefaultCode();
    })
  },
  methods: {
    // 执行数据搜索
    handleSerachSubmit(cPage) {
      const params = this.paramsSet(cPage);
      this.handleGetDealRecords(params)
    },

    // 设置交易对默认值
    setDefaultCode() {
      this.formSerach.coinCode = 'EOS/USDT';
      this.formSerach.symbolId = '230';
      this.codeList = this.codeListData.filter(v => v.symbolFormat.indexOf(this.formSerach.coinCode.toUpperCase()) > -1);
      this.inputchange();
    },

    // 参数设定
    paramsSet(cPage) {
      const accountInfo = localStorage.getItem('accountInfo');
      this.formSerach.account = JSON.parse(accountInfo).account;
      const form = this.formSerach;
      const currPage = cPage || form.currPage;
      form.currPage = currPage;
      const token = localStorage.getItem('Frontend-Token');
      const language = this.$store.state.app.language;
      const isdate = form.dateArr && form.dateArr.length > 1;
      const params = {
        token, // token信息
        account: form.account, // EOS账号
        language, // 语言(en,zh-CN,zh-TW,ko)
        channel: form.channel, // 渠道来源(web,dapp,ios,android)
        ref: '', // 钱包来源
        chain: form.coinType, // 分叉链代码
        project: '', // 项目名称
        currPage,
        pageSize: form.pageSize,
        orderByName: '',
        orderByType: '',
        symbolId: form.symbolId, // 交易对ID
        accountNo: form.accountNo, // 账号
        direction: form.direction, // 交易方向：1-买入；2-卖出
        beginDate: isdate ? form.dateArr[0] : '', // 开始时间（yyyy-MM-dd）
        endDate: isdate ? form.dateArr[1] : '', // 结束时间（yyyy-MM-dd）
      };
      return params
    },

    // 清除搜索条件
    handleClearSubmit() {
      this.formSerach.dateArr = []; // 日期范围
      this.formSerach.direction = ''; // 方向
      this.formSerach.coinType = ''; // 主链
      this.formSerach.account = ''; // 账户
      this.formSerach.symbolId = '';
      this.formSerach.coinCode = '';
    },

    // 查询成交记录
    handleGetDealRecords(params) {
      this.$http.post('/dealRecord/queryDealRecords', params).then((res) => {
        if (res.code !== 0) {
          this.$message.error(res.msg);
          return;
        }
        this.tableData = res.page.list;
        this.formSerach.totalCount = res.page.totalCount;
      });
    },

    // 显示币种列表
    handleShowCodeList() {
      if (!this.formSerach.coinCode) {
        this.formSerach.symbolId = '';
        this.formSerach.coinCode = '';
        return;
      }
      this.codeList = this.codeListData.filter(v => v.symbolFormat.indexOf(this.formSerach.coinCode.toUpperCase()) > -1);
      if (!this.codeList.length) {
        this.historyVisible = false;
      } else {
        this.historyVisible = true;
      }
    },
    // 选择币种列表
    handleSelectCodeList(item) {
      this.historyVisible = false;
      this.formSerach.coinCode = item.symbolFormat;
      this.formSerach.symbolId = item.id;
      this.historyList.unshift(item.symbolFormat);
      this.historyList = Array.from(new Set(this.historyList));
      this.codeList = [item];
      if (this.historyList.length > 6) {
        this.historyList.pop();
      }
      localStorage.setItem('historyDatas', JSON.stringify(this.historyList));
      this.handleSerachSubmit();
    },
    // 选择历史记录
    handleSelectHistory(item, index) {
      if (this.isClick) {
        this.historyVisible = false;
        this.$refs.historyInput.blur();
        this.formSerach.coinCode = item;
        this.historyList.splice(index, 1);
        this.historyList.unshift(item);
        localStorage.setItem('historyDatas', JSON.stringify(this.historyList));
        const itemId = this.codeListData.find(v => v.symbolFormat === item).id;
        this.formSerach.symbolId = itemId;
        const items = {
          id: itemId,
          symbol: item
        };
        this.codeList = [items];
        this.handleSerachSubmit();
        this.isClick = false;
        setTimeout(() => {
          this.isClick = true;
        }, 200);
      }
    },
    // 重置搜索
    handleInitSearch() {
      this.formSerach.symbolId = '';
      this.formSerach.coinCode = '';
    },

    // 分页
    handleSizeChange(val) {
      this.formSerach.pageSize = val;
      this.handleSerachSubmit();
    },

    // 选中页
    handleCurrentChange(val) {
      this.formSerach.currPage = val;
      this.handleSerachSubmit();
    },

    // 获取选择时间
    listenTimeArr(val) {
      this.formSerach.dateArr = val;
    },

    // 链的logo
    chainLogo(val) {
      return chainLogo(val)
    },

    // 拷贝反馈
    onCopy() {
      this.$message.success(this.$t('myWallet.copySuccess'));
    },
    onError() {
      this.$message.error(this.$t('myWallet.copyError'));
    },
    // data set
    dataReset() {
      // 交易方向
      this.directionList = [
        {
          value: '',
          label: this.$t('order.all'),
          language: 'all',
        },
        {
          value: 1,
          label: this.$t('order.buy'),
          language: 'buy',
        },
        {
          value: 2,
          label: this.$t('order.sell'),
          language: 'sell',
        }
      ];
      // 主链币种
      this.coinTypeList = [
        {
          value: '',
          label: this.$t('order.all'),
        },
        {
          value: 'eos',
          label: 'EOS',
        },
        {
          value: 'bos',
          label: 'BOS',
        },
        {
          value: 'meetone',
          label: 'MEETONE',
        },
        {
          value: 'enu',
          label: 'ENU',
        },
        {
          value: 'fibos',
          label: 'FIBOS',
        },
        {
          value: 'telos',
          label: 'TELOS',
        },
        {
          value: 'wax',
          label: 'WAX',
        },
        {
          value: 'lynx',
          label: 'LYNX',
        }
      ];
      // 交易角色
      this.roleList = [
        {
          value: '',
          label: this.$t('order.all'),
        },
        {
          value: 1,
          label: 'Make'
        },
        {
          value: 2,
          label: 'Take'
        },
      ];
    },

    // 订单导出 -- 询问
    handleExportOrder() {
      if (this.hasDataForTable === 0) {
        this.$message.warning(this.$t('order.noOrderExport'));
        return;
      }
      this.$confirm(this.$t('order.limitOrder'), this.$t('public.reTip'), {
        confirmButtonText: this.$t('public.sure'),
        cancelButtonText: this.$t('public.cancel'),
        center: true,
      }).then(() => {
        // 订单导出 -- 授权
        const token = localStorage.getItem('Frontend-Token');
        if (token) {
          // 判断订单导出次数
          this.handleJudgeExportNum((res) => {
            if (res !== 'error') {
              if (res === 0) {
                this.$message.error(this.$t('order.pleaseTryAgain'));
                return;
              }
              this.handleExportOrderAction();
            }
          });
        }
      }).catch(() => {});
    },
    // 判断导出次数剩余
    handleJudgeExportNum(callback) {
      this.$http.post('/order/getRemainExportCount').then((res) => {
        if (res.code !== 0) {
          this.$message.error(this.$t('order.exportError'));
          callback('error');
          return;
        }
        callback(res.remainExportCount);
      });
    },
    // 订单导出 -- 执行导出操作
    handleExportOrderAction() {
      const params = this.paramsSet();
      this.$http.post('/dealRecord/exportDealRecords', params, {
        responseType: 'blob',
      }).then((res) => {
        this.$message.success(this.$t('order.exportSuccess'));
        const blob = new Blob([res]);
        const fileName = 'Newdex - 成交记录.xls';
        const elink = document.createElement('a');
        elink.download = fileName;
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink);
      });
    },
    inputchange() {
      this.$forceUpdate()
    }
  },
};
</script>

<style lang="scss" scoped>
  @import '@/assets/css/variables.scss';

  .partnerMain {
    background: #fff;
    width: 100%;
    min-width: 1380px;
    min-height: 88vh;

    .partnerLoginedMain {
      max-width: 1700px;
      margin: auto;
      padding: 40px 80px;
      height: 100%;
      box-sizing: border-box;
    }

    .formSerach-inline {
      /deep/.el-form--inline .el-form-item {
        margin-bottom: 10px;
      }
    }

    .tablebox {
      border: 1px solid #ebeef5;

      .tridbox {
        span {
          vertical-align: middle;

          &:last-child{
            color: #278EDA;
            cursor: pointer;
          }
        }
      }
    }

    .contentTop {
      margin-top: 10px;
      margin-bottom: 30px;
      justify-content: flex-start;
      flex-wrap: wrap;


      .datebox {
        min-width: 280px;
        margin: 0 20px 0 0;
        border: 1px solid #ebeef5;
        padding: 10px;

        .flexb {
          margin-top: 5px;

          span {
            padding: 0 10px;
          }
        }
      }

      .optionChain {
        text-align: center;
        padding-bottom: 10px;

        img {
          width: 19px;
          display: inline-block;
          vertical-align: middle;
          margin-bottom: 2px;
        }

        span {
          display: inline-block;
          vertical-align: middle;
        }
      }
    }
  }

  .theme-1B1D27 #app {
    .partnerMain {
      background: transparent;

      .contentTop {
        .datebox {
          background-color: #152247 !important;
        }

        .datebox {
          border: 1px solid #4e5b85 !important
        }
      }

      .tablebox {
        border: 1px solid #4e5b85 !important;

        /deep/ .el-table__body-wrapper .cell {
          color: RGBA(197, 206, 228, 0.5) !important;
        }

        /deep/ .has-gutter .cell {
          color: RGBA(197, 206, 228, 1) !important;
        }
      }
    }
  }

  @media screen and (max-width: 1450px) {
    .partnerMain {
      .form-item-min /deep/.el-form-item__content {
      }
      .partnerLoginedMain {
        padding: 30px 20px;
      }
    }
  }
</style>
